<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model="queryCategoryIdList"
            @change="handleCategoryChange"
        />
      </el-form-item>
      <el-form-item label="规格名称" prop="specName">
        <el-input
            placeholder="请输入规格名称"
            v-model="queryParams.specName"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            @click="handleUpdate"
            :disabled="showEdit"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="showDelete"
            @click="handleDelete('')"
        >删除
        </el-button>
      </el-col>
      <right-toolbar></right-toolbar>
    </el-row>

    <el-table :data="specList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分类名称" prop="categoryName" width="120"/>
      <el-table-column label="规格名称" align="left" prop="specName" width="120"/>
      <el-table-column label="规格值" #default="scope">
        <div
            v-for="(item1, index1) in scope.row.specValueList"
            :key="index1"
            style="padding: 5px; margin: 0;width: 100%;"
        >
          {{ item1.key }}：
          <span
              v-for="(item2, index2) in item1.valueList"
              :key="index2"
              class="div-atrr"
          >
          {{ item2 }}
        </span>
        </div>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="specRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="规格名称" prop="specName">
          <el-input v-model="form.specName" placeholder="请输入规格名称"/>
        </el-form-item>
        <el-form-item>
          <div
              v-for="(item1, index1) in specValueList"
              :key="index1"
              style="padding: 10px; margin: 0;"
          >
            {{ item1.key }}：
            <span
                v-for="(item2, index2) in item1.valueList"
                :key="index2"
                class="div-atrr"
            >
        {{ item2 }}
      </span>
            <el-button size="small" @click="removeAttr(index1)">删除</el-button>
            <br/>
          </div>
        </el-form-item>
        <el-form-item label="">
          <el-row v-if="isAdd">
            <el-col :span="10">
              <el-input
                  v-model="specValue.key"
                  placeholder="规格"
                  style="width: 90%;"
              />
            </el-col>
            <el-col :span="10">
              <el-input
                  v-model="specValue.values"
                  placeholder="规格值(如:白色,红色)"
                  style="width: 90%;"
              />
            </el-col>
            <el-col :span="4">
              <el-button size="default" @click="addSpecValue">添加</el-button>
            </el-col>
          </el-row>
          <el-row v-if="!isAdd">
            <el-col :span="4" align="left">
              <el-button size="default" @click="isAdd = true">
                添加新规格
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  productSpecPageList,
  addProductSpec,
  productSpecList,
  updateProductSpec,
  deleteProductSpec
} from "@/api/product/productSpec.js"
import {getCategoryById} from "@/api/product/category.js"
import {getCurrentInstance, ref} from 'vue'

// 表格数据模型
const specList = ref([])
const {proxy} = getCurrentInstance()
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {   // 加载数据的方法
    if (typeof node.value == "undefined") node.value = 0
    const {data} = await getCategoryById(node.value)
    data.forEach(item => {
      item.leaf = !item.hasChildren
    })
    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)
//传给后端的json数据
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    categoryId: null,
    specName: null
  },
  form: {},
  rules: {
    categoryIdList: [
      {required: true, message: "分类不能为空", trigger: "change"}
    ],
    specName: [
      {required: true, message: "规则名称不能为空", trigger: "blur"}
    ]
  }
})
const {queryParams, form, rules} = toRefs(data)
// 分页条数据模型
const total = ref(0)

function getList() {
  productSpecPageList(queryParams.value).then(res => {
    specList.value = res.rows
    total.value = res.total
    specList.value.forEach(item => {
      item.specValueList = JSON.parse(item.specValue)
    })
  })
}

const queryCategoryIdList = ref([])

function handleCategoryChange() {
  queryParams.value.categoryId = queryCategoryIdList.value[2]

}

//搜索按钮
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryCategoryIdList.value = []
  proxy.resetForm("queryRef");
  queryParams.value.categoryId = null
  queryParams.value.specName = ''
  handleQuery();
}

getList()
const open = ref(false)
const title = ref("添加商品规格信息")
//新增按钮
const isAdd = ref(false)
const specValue = ref({key: '', values: ''})
const specValueList = ref([])

function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品规格信息"
  specValueList.value = []
}

//表单清空
function reset() {
  form.value = {
    id: null,
    specName: null,
    specValue: null,
    categoryId: null,
    categoryIdList: []
  };
  proxy.resetForm("specRef");
}

//表单中的添加按钮
function addSpecValue() {
  specValueList.value.push({
    key: specValue.value.key,
    valueList: specValue.value.values.split(",")
  })
  specValue.value = {}
  isAdd.value = false
}

//表单中删除按钮
function removeAttr(index) {
  specValueList.value.splice(index, 1)
}

//提交表单
function submitForm() {
  proxy.$refs['specRef'].validate(valid => {
    if (valid) {
      form.value.specValue = JSON.stringify(specValueList.value)
      form.value.categoryId = form.value.categoryIdList[2]
      if (form.value.id != null) {
        updateProductSpec(form.value).then(res => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProductSpec(form.value).then(res => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

//取消按钮
function cancel() {
  open.value = false
  reset()
}

//修改之前的回显
function handleUpdate(id) {
  reset()
  title.value = "修改商品规格信息"
  const _ids = id || ids.value
  productSpecList(_ids).then(res => {
    form.value = res.data
    open.value = true
    specValueList.value = JSON.parse(form.value.specValue)
  })
}

//批量操作
const ids = ref([]);
let showDelete = ref(true)
let showEdit = ref(true)

function handleSelectionChange(val) {
  ids.value = val.map(item => item.id)
  form.value.id = ids.value[0];
  showEdit.value = val.length != 1
  showDelete.value = !val.length
}

//删除功能
function handleDelete(id){
  const _ids = id || ids.value
  proxy.$modal.confirm('是否确认删除商品规格编号为"' + _ids + '"的数据项？').then(function() {
    return deleteProductSpec(_ids);
  }).then(res=>{
    getList()
    proxy.$modal.msgSuccess("删除成功");
  })
}
</script>
<style scoped>
.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}
</style>